/*
 * @author: Victor
 * @Date: 2021-08-19 00:01:26
 * @LastEditTime: 2021-08-19 16:07:01
 */
$(function () {
  $('#link-reg').click(function () {
    $('.login-box').hide().siblings('.reg-box').show();
  });
  $('#link-login').click(function () {
    $('.reg-box').hide().siblings('.login-box').show();
  });

  var form = layui.form;
  var layer = layui.layer;
  form.verify({
    // 自定义命名为pwd的校验规则
    pwd: [/^[\S]{6,12}$/, '密码必须为6到12位且不能出现空格'],
    // 自定义确认密码校验规则
    repwd: function (value) {
      var pswd = $('.reg-box input[name="password"]').val();
      if (pswd != value) {
        return '两次输入密码不一致';
      }
    },
  });

  // 注册
  $('#reg-form').submit(function (e) {
    e.preventDefault();
    var data = {
      username: $('#reg-form input[name="username"]').val(),
      password: $('#reg-form input[name="password"]').val(),
    };
    $.post('/api/reguser', data, function (res) {
      if (res.status != 0) {
        return layer.msg(res.message);
      }
      layer.msg('注册成功，请登录');
      $('#link-login').click();
    });
  });

  // 登录
  $('#login-form').submit(function (e) {
    e.preventDefault();
    $.post('/api/login', $(this).serialize(), function (res) {
      if (res.status != 0) {
        return layer.msg('登录失败');
      }
      layer.msg('登录成功');
      localStorage.setItem('token', res.token);
      location.href = 'index.html';
    });
  });
});
